<template>
  <section class="imgupload">
    <el-upload
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :on-change="handleChange"
      :class="{active: plusShow}"
      :before-upload="beforeUpload"
      :http-request=" uploadImg"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="percentIsSshow" :percentage="percent" style="width: 200px" />
    <el-dialog :visible.sync="dialogVisible" width="25%" title="图片预览">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </section>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDc4HGzZy97uXw61h8KHzSikX6QYR4TfhW',
  SecretKey: 'f5GF1YqthFZeU6TbU8WeYDdolTxFLEsH'
})
export default {
  data() {
    return {
      percentIsSshow: false,
      percent: 0,
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      curID: ''
    }
  },
  computed: {
    plusShow() {
      return this.fileList.length === 1
    }
  },
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    handleChange(file, fileList) {
      this.fileList = fileList.map(item => item)
    },
    beforeUpload(file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      const maxsize = 5 * 1024 * 1024
      if (!types.includes(file.type)) {
        this.$message.error('上传的格式只能是jpeg gif bmp png格式')
        return false
      }
      if (file.size > maxsize) {
        this.$message.error('文件的大小不能超过5m')
        return false
      }
      this.curID = file.uid
      this.percentIsSshow = true
      return true
    },
    uploadImg(params) {
      if (params.file) {
        cos.putObject({
          Bucket: 'adim-amec-1313337986', /* 填入您自己的存储桶，必须字段 */
          Region: 'ap-guangzhou', /* 存储桶所在地域，例如ap-beijing，必须字段 */
          Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
          StorageClass: 'MAZ_STANDARD',
          Body: params.file, // 上传文件对象
          onProgress: progressData => {
            // console.log(JSON.stringify(progressData))
            this.percent = progressData.percent * 100
          }
        }, (err, data) => {
          // console.log(err || data)
          // console.log(err)
          if (!err && data.statusCode === 200) {
            this.fileList = this.fileList.map(el => {
              if (el.uid === this.curID) {
                return { url: `http://${data.Location}`, upload: true }
              }
              return el
            })
          }
          setTimeout(() => {
            this.percentIsSshow = false
            this.percent = 0
          }, 1000)
        })
      }
    }
  }
}
</script>

<style lang="scss">
  .imgupload {
    .active{
      .el-upload{
        display: none;
      }
    }
    .el-dialog__headerbtn{
      top: 8px;
    }
  }
</style>

